#coding=utf-8
'''
Created on 2017-7-15

@author: sandy
'''

import time
from twisted.internet import task
        
class LoginFailCtx(object):
    
    def __init__(self):
        self.failtimes = 0
        self.time = time.time()

class TimeCheck(object):
    
    def __init__(self):
        self.__loginfailmap = {}
    
    def start(self):
        l = task.LoopingCall(self.onTimer)
        l.start(2, False)
    
    def stop(self):
        pass
    
    def onTimer(self):
        now = time.time()
        self.checkLoginFail(now)
    
    ###########################################################
    def addLoginFail(self, uid):
        ctx = self.__loginfailmap.get(uid)
        if not ctx:
            ctx = LoginFailCtx()
            ctx.failtimes = 1
            self.__loginfailmap[uid] = ctx
        else:
            ctx.failtimes += 1
        
    def canLogin(self, uid):
        ctx = self.__loginfailmap.get(uid)
        if not ctx:
            return True
        return ctx.failtimes < 3
    
    def checkLoginFail(self, now):
        removelist = []
        for uid,ctx in self.__loginfailmap.iteritems():
            if now - ctx.time > 10:
                removelist.append(uid)
        for uid in removelist:
            self.__loginfailmap.pop(uid)        
    
instance = TimeCheck()


if __name__ == '__main__':
    pass